using System;

using Gtk;

namespace Gazebo.Core
{
    [System.ComponentModel.ToolboxItem(true)]
    public partial class ConnectionPreferencePane : Gtk.Bin, IPreferencePane
    {
        Widget IPreferencePane.PaneWidget {
            get { return this; }
        }
        
        string IPreferencePane.Path {
            get { return "/Connection"; }
        }
        
        private ListStore filterStore = new ListStore(typeof(INetworkFilterFactory));
        
        public ConnectionPreferencePane()
        {
            this.Build();
            
            CellRendererText renderer = new CellRendererText();
            filterCombo.PackStart(renderer, true);
            filterCombo.SetCellDataFunc(renderer, FilterDataFunc);
            filterCombo.Model = filterStore;
            
            BuildFilterList();
            
            hostnameEntry.Text = CorePreferences.Instance.ServerHostname;
            portEntry.Text = CorePreferences.Instance.ServerPort.ToString();
        }
        
        private void BuildFilterList()
        {
            TreeIter iter = filterStore.Append();
            filterCombo.SetActiveIter(iter);
            
            var factories = AddinUtilities.GetExtensionObjects<INetworkFilterFactory>("/Gazebo/Client/NetworkFilter");
            
            foreach (INetworkFilterFactory factory in factories) {
                iter = filterStore.AppendValues(factory);
                
                if (CorePreferences.Instance.NetworkFilterFactory == factory) {
                    filterCombo.SetActiveIter(iter);
                }
            }
        }
        
        private static void FilterDataFunc(CellLayout layout, CellRenderer r,
                                           TreeModel model, TreeIter iter)
        {
            INetworkFilterFactory factory = (INetworkFilterFactory) model.GetValue(iter, 0);
            CellRendererText rtext = (CellRendererText) r;
            
            if (factory == null) {
                rtext.Text = "(None)";
            } else {
                rtext.Text = factory.Label;
            }
        }
        
        private INetworkFilterFactory GetSelectedFilter()
        {
            TreeIter iter;
            
            if (!filterCombo.GetActiveIter(out iter)) {
                return null;
            }
            
            return (INetworkFilterFactory) filterStore.GetValue(iter, 0);
        }
        
        void IPreferencePane.Apply()
        {
            CorePreferences.Instance.ServerHostname = hostnameEntry.Text;
            CorePreferences.Instance.ServerPort = int.Parse(portEntry.Text);
            CorePreferences.Instance.NetworkFilterFactory = GetSelectedFilter();
            CorePreferences.Instance.Save();
        }
    }
}
